package com.xlhj.yucloud.web.service;

import com.xlhj.yucloud.common.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: liucaijing
 * @description: TokenService
 * @date: 2021/9/10 7:59
 */
@Component
public class TokenService {

    @Value("${token.header}")
    private String header;
    @Value("${token.secret}")
    private String secret;
    @Value("${token.expireTime}")
    private Long expiration;
    @Autowired
    private RedisService redisService;

    /**
     * 生成token令牌
     * @param userName
     * @return
     */
    public String generateToken(Long userId, String userName) {
        Map<String, Object> claims = new HashMap<>(3);
        claims.put("id", userId);
        claims.put("sub", userName);
        claims.put("created", new Date());
        return generateToken(claims);
    }

    /**
     * 从claims生成令牌
     * @param claims
     * @return
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setIssuedAt(new Date())
                .setIssuer("yu-cloud")
                .setExpiration(new Date(Instant.now().toEpochMilli() + expiration))
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }



    /**
     * 从token令牌中获取数据声明
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 判断令牌是否过期
     * @param claims
     * @return
     */
    public Boolean isTokenExpired(Claims claims) {
        try {
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新令牌
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put("created", new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 从令牌中获取用户名
     * @param token
     * @return
     */
    public String getUserNameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求的token
     * @param request
     * @return
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(this.header);
        if (StringUtils.hasLength(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

}
